package com.ganbo.thread;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 验证使用SimpleDateFormate线程不安全问题
 * Created by gan on 2020/5/21 23:11.
 */
public class SimpleDateFormatThreadSafeDemo extends Thread {

    private SimpleDateFormat sf;
    private List<String> list;      //要格式化的字符串

    public SimpleDateFormatThreadSafeDemo(SimpleDateFormat sf, List<String> list) {
        this.sf = sf;
        this.list = list;
    }

    public void formate() throws ParseException {

        for (String str : list) {
            Date parse = sf.parse(str);
            String format = sf.format(parse);
            if (!str.equals(format))
                System.err.println(Thread.currentThread().getName() + " 传入之前的字符串:" + str + " 格式化解析之后的字符串为:" + format);
            else
                System.out.println(Thread.currentThread().getName() + "  " + Thread.currentThread().getId());
        }
    }

    @Override
    public void run() {
        try {
            formate();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> list = Arrays.asList("2001-01-02", "2002-01-02", "2002-01-02", "2002-01-02",
                "2002-01-03", "2002-01-04", "2002-01-05", "2002-01-06", "2002-01-07", "2002-01-08"
                , "2002-01-09", "2002-01-10", "2002-01-11", "2002-01-12", "2002-01-13", "2002-01-14");

        SimpleDateFormatThreadSafeDemo[] std = new SimpleDateFormatThreadSafeDemo[10];
        for (int i = 0; i < std.length; i++) {
            std[i] = new SimpleDateFormatThreadSafeDemo(sf, list);
        }

        for (int i = 0; i < std.length; i++) {
            std[i].start();
        }

    }
}
